<template>
  <div class="qa-session">
    <div class="qa-container">
      <div class="qa-info">
        <div class="course-info">
          <h2>{{ course.title }}</h2>
          <span class="teacher-name">讲师: {{ course.teacherName }}</span>
        </div>
        <el-tag v-if="isTeacher" type="success">教师端</el-tag>
        <el-tag v-else type="info">学生端</el-tag>
      </div>

      <div class="qa-main">
        <div class="chat-wrapper">
          <Chat
            :conversation-id="conversationId"
            :current-user-id="currentUserId"
            :recipient-id="isTeacher ? studentId : course.teacherId"
            :enable-video="true"
          />
        </div>

        <div class="sidebar">
          <div class="online-users">
            <h3>在线用户</h3>
            <el-scrollbar height="200px">
              <div
                v-for="user in onlineUsers"
                :key="user.id"
                class="user-item"
                :class="{ 'is-teacher': user.role === 'TEACHER' }"
              >
                <el-avatar :size="32" :src="user.avatar" />
                <span class="user-name">{{ user.name }}</span>
                <el-tag size="small" :type="user.role === 'TEACHER' ? 'success' : 'info'">
                  {{ user.role === 'TEACHER' ? '教师' : '学生' }}
                </el-tag>
              </div>
            </el-scrollbar>
          </div>

          <div class="qa-resources">
            <h3>课程资料</h3>
            <el-scrollbar height="200px">
              <el-tree
                :data="courseResources"
                :props="defaultProps"
                @node-click="handleResourceClick"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <el-icon><Document /></el-icon>
                    <span>{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import Chat from '@/components/Chat.vue'
import { Document } from '@element-plus/icons-vue'

const route = useRoute()
const userStore = useUserStore()

const course = ref({})
const onlineUsers = ref([])
const courseResources = ref([])
const conversationId = ref('')
const currentUserId = ref('')
const studentId = ref('')

const isTeacher = computed(() => {
  return userStore.userRole === 'TEACHER'
})

const defaultProps = {
  children: 'children',
  label: 'name'
}

// 初始化WebSocket连接
const initializeWebSocket = () => {
  const client = new Client({
    brokerURL: 'ws://localhost:8080/ws',
    onConnect: () => {
      // 订阅在线用户更新
      client.subscribe(`/topic/course/${route.params.courseId}/users`, (message) => {
        onlineUsers.value = JSON.parse(message.body)
      })
      
      // 加入课程房间
      client.publish({
        destination: '/app/course.join',
        body: JSON.stringify({
          courseId: route.params.courseId,
          userId: currentUserId.value,
          userRole: isTeacher.value ? 'TEACHER' : 'STUDENT'
        })
      })
    }
  })
  client.activate()
  return client
}

const loadCourseData = async () => {
  try {
    const { data } = await getCourseDetails(route.params.courseId)
    course.value = data
    conversationId.value = `course_${route.params.courseId}`
    currentUserId.value = userStore.userId
  } catch (error) {
    ElMessage.error('获取课程信息失败')
  }
}

const loadCourseResources = async () => {
  try {
    const { data } = await getCourseResources(route.params.courseId)
    courseResources.value = data
  } catch (error) {
    ElMessage.error('获取课程资料失败')
  }
}

const handleResourceClick = (data) => {
  if (data.type === 'file') {
    window.open(data.url, '_blank')
  }
}

let wsClient

onMounted(async () => {
  await loadCourseData()
  await loadCourseResources()
  wsClient = initializeWebSocket()
})

onUnmounted(() => {
  if (wsClient) {
    wsClient.deactivate()
  }
})
</script>

<style scoped>
.qa-session {
  padding: 20px;
  height: 100vh;
}

.qa-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
}

.qa-info {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.qa-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-wrapper {
  flex: 1;
  border-right: 1px solid #ebeef5;
}

.sidebar {
  width: 300px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 4px;
}

.user-item:hover {
  background-color: #f5f7fa;
}

.user-item.is-teacher {
  background-color: #f0f9eb;
}

.qa-resources {
  flex: 1;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>